<?php
namespace app\easytask\controller;

use cmf\controller\AdminBaseController;
use MongoDB\BSON\Binary;
use think\Db;
use think\db\Query;
use think\model\concern\TimeStamp;
#↓↓↓处理phpoffice库↓↓↓
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use plugins\dingding\lib\Dingding;


class AdminIndexController extends AdminBaseController
{
    /*
    * 任务列表，查询页面
    */
    protected $PHONE_NUMBER = '17805902037';
    public function index()
    {
        $keyword = $this-> request->param('keyword');  // 获取输入的关键字
        $starttime = $this->request->param('starttime');
        $endtime = $this->request->param('endtime');

        $user = cmf_get_current_user();
        if(!$user)$user['mobile'] = $this->PHONE_NUMBER;

        if(empty($keyword) && empty($starttime) && empty($endtime)) {   // 关键字时间范围都为空时查找全部
            $list1 = Db::name('tasks')->where("publisher", $user['mobile'])->select()->order('creat_time', 'desc');
            $list2 = Db::name('tasks')->whereLike("t_cc", '%'.$user['mobile'].'%')->select()->order('creat_time', 'desc');
        }
        elseif (empty($keyword) && !empty($starttime) && !empty($endtime)){     // 关键字为空但时间范围不空，按时间范围筛选
            $list1 = Db::name('tasks')->where("publisher",$user['mobile'])->whereBetween('creat_time',[$starttime,$endtime])->select()->order('creat_time','desc');
            $list2 = Db::name('tasks')->whereLike("t_cc", '%'.$user['mobile'].'%')->whereBetween('creat_time',[$starttime,$endtime])->select()->order('creat_time','desc');
        }
        elseif ($keyword && empty($starttime) && empty($endtime)){   //关键字不空但时间范围空，按关键字模糊查寻
            $keyword = '%' . $keyword . '%';
            $list1 = Db::name('tasks')->where("publisher",$user['mobile'])->whereLike('title', $keyword)->select()->order('creat_time','desc');
            $list2 = Db::name('tasks')->whereLike("t_cc", '%'.$user['mobile'].'%')->whereLike('title', $keyword)->select()->order('creat_time','desc');
        }

        else
        {
            $keyword = '%' . $keyword . '%';
            $list1 = Db::name('tasks')->where("publisher",$user['mobile'])->whereLike('title', $keyword)->whereBetween('creat_time',[$starttime,$endtime])->select()->order('creat_time','desc');
            $list2 = Db::name('tasks')->whereLike("t_cc", '%'.$user['mobile'].'%')->whereLike('title', $keyword)->whereBetween('creat_time',[$starttime,$endtime])->select()->order('creat_time','desc');
        }

        $this->assign('tasks1',$list1);
        $this->assign('tasks2',$list2);
        return $this->fetch();

    }

    /*
     * 手动发布任务提交
     */
    public function fresh($task_id){
        $total = Db::name('receive')->where('task_id',$task_id)->count();
        $inner = Db::name('receive')->where('task_id',$task_id)->where('finished',3)->count();
        Db::name('tasks')->where('task_id',$task_id)->update(['total'=>$total,'inner_finished'=>$inner]);
    }
    public function addPost()   // 插入数据库的方法，输入的信息传入addpost
    {
        $data = $this->request->param();        //获取输入的信息

        $t = date('Y-m-d H:i:s');
        $data['creat_time']=$t;

        $file_names = [];
        if (!empty($data['file_names']) && !empty($data['file_urls'])) {
            foreach ($data['file_urls'] as $key => $url) {
                $fileUrl = cmf_asset_relative_url($url);
                array_push($file_names, ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
            }
        }
        $data['file_names'] = json_encode($file_names);

       ###############################

        $taskid = Db::name('tasks')->insertGetId($data);
        Db::name('tasks')->where('task_id',$taskid)->update(['total' => 1 ,'inner_finished' => 0]);
        ####################################

        $data['task_id'] = $taskid;
        Db::name('receive')->insert($data);
        $this->success('添加成功', url('AdminIndex/index'));


    }
    /*
     * 手动发布任务
     */
    public function add()
    {
        $this->assign('opening','');
        return $this->fetch();
    }
    /*
     * 导入任务
     */
    public function add2()
    {
        return $this->fetch();
    }
    /*
     * 导入任务提交
     */
    public function edit_detail(){
        $dd = $this->request->param();
        $change = Db::name('receive')->where('receive_id',$dd['ids'])->find();
        $this->assign('task_id',$dd['task_id']);
        $this->assign('list',$change);
        return $this->fetch();
    }
    public function edit_post(){
        $task = $this->request->param();
        Db::name('receive')->update($task);
        $this->success('修改成功', url('AdminIndex/details',['task_id'=>$task['task_id']]));
    }
    public function add2Post()
    {
        $data = $this->request->param();//获取输入的信息
        $t = date('Y-m-d H:i:s');
        $data['creat_time']=$t;
        $data['inner_finished'] = 0;
        unset($data['appendix']);
        $user = cmf_get_current_user();
        if(!$user)$user['mobile'] = $this->PHONE_NUMBER;

        $backid = Db::name('tasks')->insertGetId($data);
        unset($data['']);
        unset($data['t_cc']);

        $excelfile = $this->request->param('appendix');
        if ($excelfile) {
            $excelfile = CMF_ROOT . "public/upload/" . $excelfile;
            $exceldata = $this->importExcel($excelfile,$data);
        }
        $tasknumber = 0;
        $mobiles = array();
        foreach ($exceldata as &$value) {
            $value['task_id'] = $backid;
            $value['receiver'] = (int)$value['receiver'];
            $value['finished'] = 1;
            $value['publisher'] = $user['mobile'];
            $value['publish_content'] = $data['task_content'];
            unset($value['inner_finished']);
            Db::name('receive')->insert($value);
            $tasknumber += 1;
//获取接收人手机号
            $mobiles[] = $value['receiver'];
        }
        //转化手机号为钉钉用户id，发送工作通知
//        if(!empty($mobiles)){
//            $userids = mobile2dduserid($mobiles);
//            $corp = session('corp');
//            $app = session(('app'));
//            $ding = new Dingding($corp,$app);
//            $msg=array('title'=>$data['title'],'subtitle'=>mb_substr($data['task_content'], 0, 10, 'utf-8'),'url'=>url('AdminIndex/index'),'picurl'=>'');
//            if(!empty($userids))$ding->sendNotice($msg,$userids);
//        }


        Db::name('tasks')->where('task_id',$backid)->update(['total' => $tasknumber ,'publisher' => $user['mobile']]);
        $this->success('添加成功', url('AdminIndex/index'));
    }

//    public function notice(){
//        $current = date('Y-m-d H:i:s');
//        $list = Db::name('receive')->where();
//    }



    protected function importExcel($excelfile,$data){
        #处理并返回一个可以逐条插入的数据
        $spreadsheet = IOFactory::load($excelfile);
        $countSheet = $spreadsheet -> getSheetCount();
        $sheet_number = 0;
        $backdata = [];
        while($sheet_number<$countSheet){


            $sheet  = $spreadsheet->getSheet($sheet_number);//sheet
            $highestRow = $sheet->getHighestRow(); // 取得总行数
            $inner = $sheet->toArray();
            for ($row = 1;$row < $highestRow;$row++){
                $tempdata = $data;
                $tempdata['receiver'] = $inner[$row][1];
                $tempdata['remarks'] = $inner[$row][2];
                $col = 3;
                #开始拼接字段
                $tempcontent = '';
                while(1) {
                    try {
                        $tempcontent = $tempcontent . $inner[0][$col] . ':' . $inner[$row][$col] . '<br>';
                        $col ++;
                    } catch (\Throwable $e) {
                        break;
                    }
                }
                $tempdata['task_content'] = $tempcontent;
                array_push($backdata,$tempdata);
            }
            $sheet_number++;
        }
        return $backdata;

    }
    /*
     * 删除任务
     */
    public function delete()
    {
        $id = $this->request->param('task_id');
        $result = Db::name('tasks')->where('task_id',$id)->delete();
        Db::name('receive')->where('task_id',$id)->delete();
        $this->success('删除成功',url('AdminIndex/index'));
    }
    public function delete_detail(){

        $id = $this->request->param('ids');
        $task = $this->request->param('task_id');
        try {
            foreach ($id as $vo) {
                Db::name('receive')->where('receive_id', $vo)->delete();
            }
        }catch (\Throwable $e){
            Db::name('receive')->where('receive_id', $id)->delete();
        }
        $this->fresh($task);
        $this->success('删除成功',url('AdminIndex/details',["task_id"=>$task]));
    }
    public function delete_details()
    {
        $id = $this->request->param('receive_id');
        $ids = $this->request->param('task_id');
        $result = Db::name('receive')->where('receive_id',$id)->delete();
        $this->success('删除成功',url('AdminIndex/details',['task_id'=>$ids]));
    }


    public function details()
    {
        $id = $this->request->param('task_id');
        $list1 = Db::name('tasks')->where('task_id', $id)->find();
        $nick_name = Db::name('user')->where('mobile', $list1['publisher'])->find()['user_nickname'];
        $list1['user_nickname'] = $nick_name;
        $this->assign('list', $list1);


        $list2 = Db::name('receive')->where('task_id', $id);
        $keyword = $this->request->param('keyword');
        $option = $this->request->param('filter');
        if(!empty($keyword)) {
            switch ($option){
                case 0:
                    $list2 = $list2->where('receiver',$keyword);
                    break;
                case 1:
                    $keyword = '%' . $keyword . '%';
                    $list2 = $list2->whereLike('remarks',$keyword);
                    break;
                case 2:
                    $keyword = '%' . $keyword . '%';
                    $list2 = $list2->whereLike('deakline',$keyword);
                    break;
            }
        }





        $finished = (int)$this->request->param("finished");
        if(!$finished or $finished == 0){
            $this->assign('finished',$finished);
            $list2 = $list2->select();
        }
        else{
            $this->assign('finished',$finished);
            $list2 = $list2->where('finished',$finished)->select();

        }
        $detail_list = [];
        foreach($list2 as &$vo){
            $nick_name = Db::name('user')->where('mobile', $vo['receiver'])->find()['user_nickname'];
            $vo = $vo + array('user_nickname'=>$nick_name);
            array_push($detail_list,$vo);
        }

        $user = cmf_get_current_user();
        if(!$user)$user['mobile'] = $this->PHONE_NUMBER;

        if($list1['publisher'] == $user['mobile']) $this->assign('authority',true);
        $this->assign('receive', $detail_list);

        return $this->fetch();
    }
    public function explode_post()
    {
        $newExcel = new Spreadsheet();  //创建一个新的excel文档
        $objSheet = $newExcel->getActiveSheet();  //获取当前操作sheet的对象
        $objSheet->setTitle('管理员表');

        $newExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('G')->setAutoSize(true);
        $newExcel->getActiveSheet()->getColumnDimension('H')->setAutoSize(true);
//
        $objSheet->setCellValue('A1', '处理人')
            ->setCellValue('B1', '手机号码')
            ->setCellValue('C1', '完成时间')
            ->setCellValue('D1', '任务状态')
            ->setCellValue('E1', '回复内容')
            ->setCellValue('F1', '附件')
            ->setCellValue('G1', '发布时间')
            ->setCellValue('H1', '截止时间');


        $ids = $this->request->param('ids');
        $task_id = $this->request->param('task_id');
        $sql = [];
        if($ids){
            foreach ($ids as $vo){
                array_push($sql,Db::name('receive')->where('receive_id',$vo)->find());
            }
        }
        else $sql = Db::name('receive')->where('task_id',$task_id)->select();

        $task_tital = explode('<br>',$sql[0]['task_content']);

        $col = 8;
        foreach ($task_tital as $tt){
            $newExcel->getActiveSheet()->getColumnDimensionByColumn($col)->setAutoSize(true);
            $newExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, explode(':',$tt)[0]);
            $col = $col + 1;

        }

        $count = count($sql);

        for ($i = 2; $i <= $count + 1; $i++) {
            $finished = '';
            switch ($sql[$i - 2]['finished'])
            {
                case 0:
                    break;
                case 1:
                    $finished='未读';
                    break;
                case 2:
                    $finished='已读未处理';
                    break;
                case 3:
                    $finished='已处理';
                    break;

            }
            $appendix = '无';
            if (!empty($sql[$i-2]['photo'])) $appendix = '有';
            $objSheet->setCellValue('A' . $i, $sql[$i - 2]['receiver'])
                ->setCellValue('B' . $i, $sql[$i - 2]['receiver'])
                ->setCellValue('C' . $i, $sql[$i - 2]['single_finish_time'])
                ->setCellValue('D' . $i ,$finished)
                ->setCellValue('E' . $i, $sql[$i - 2]['back_content'])
                ->setCellValue('F' . $i, $appendix)
                ->setCellValue('G' . $i,  $sql[$i - 2]['creat_time'])
                ->setCellValue('H' . $i,  $sql[$i - 2]['deadline']);
            $col = 8;

            foreach(explode('<br>',$sql[$i - 2]['task_content']) as $vo ){
                if ($vo == '')continue;
                $objSheet->setCellValueByColumnAndRow($col, $i, explode(':',$vo)[1]);
                $col += 1;
            }

        }
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=" . '任务细节' . ".xls");
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($newExcel, 'Xls');
        $objWriter->save('php://output');
        $this->success('导出成功', url('AdminIndex/index'));
    }

    public function export()
    {
        $filter = $this->request->param();
        $list = Db::name('receive')->where(function (Query $query) use ($filter) {
            $query->where('task_id','=',$filter['task_id']);
            $sense = empty($filter['sense']) ? 0 : $filter['sense'];
            if (!empty($sense)) {
                $query->where('sense', $sense);
            }

            $startTime = empty($filter['start_time']) ? 0 : $filter['start_time'];
            $endTime   = empty($filter['end_time']) ? 0 : $filter['end_time'];
            if (!empty($startTime)) {
                $query->where('create_time', '>=', $startTime);
            }
            if (!empty($endTime)) {
                $query->where('create_time', '<=', $endTime);
            }
        })->select();

        if (isset($filter['ids'])){
            $templist = [];
            foreach ($filter['ids'] as $vo){
                foreach ($list as $vvo) {
                    if ($vvo['receive_id'] == $vo) array_push($templist, $vvo);
                }
            }
            $list = $templist;
        }

        if(isset($list)){
            $name = "导出" . date('YmdHis');
            //$name = iconv('utf-8', 'GBK', $name);
            //设置脚本的最大执行时间，设置为0则无时间限制
            set_time_limit(0);
            ini_set('max_execution_time', '0');
            $filename =     CMF_ROOT . 'public/upload/downzip/' . $name . '.zip';
            $downname = $name . '.zip';
            $zip = new \ZipArchive();
            if ($zip->open($filename, \ZIPARCHIVE::CREATE) !== TRUE) {
                exit($filename .'无法打开文件，或者文件创建失败');
                return 0;
            }
            foreach ($list as $data){
                //$i = 1;
                if(!empty($data["file_names"])){
                    $more = json_decode($data["file_names"],true);
                    foreach ($more as $v) {
                        $zip->addFile(CMF_ROOT . 'public/upload/' .$v['url'],$data["remarks"] .'/' . $v['name']);
                        //$zip->addFromString($data['customer'] . '/' . $i . '.jpg', file_get_contents($v));
                        //$i++;
                    }

                }

            }
            $zip->close();
//            cmf_get_file_download_url();
            $this->assign('downurl', cmf_get_domain() ."/upload/downzip/".$downname);
            return $this->fetch();
//            $this->success("导出成功，下载中！","http://upinfo.fz.cmttfj.com/upload/downzip/".$downname);//return download($filename,$downname);
        }
        else $this->error("没有数据！",url("AdminIndex/infolist"));
    }



    public function index1(){

        $this->success('提交成功', url('AdminIndex/index'));
    }






}